package middleware

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/services"
	"GOPAAS/internal/utils"
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func Web() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		access_token_any := session.Get("access_token")
		user_id_any := session.Get("user_id")
		company_id_any := session.Get("company_id")
		lang := session.Get("lang")
		var user_id int64
		var company_id int64
		var access_token string
		e, b := sentinel.Entry("api_request", sentinel.WithTrafficType(base.Inbound))
		if b != nil {
			fmt.Println("限流了")
			utils.HttpError(c, 503, "请求繁忙", nil)
			c.Abort()
			return
		}
		if access_token_any != nil && user_id_any != nil && company_id_any != nil {
			user_id = user_id_any.(int64)
			company_id = company_id_any.(int64)
			access_token = access_token_any.(string)
			if access_token != "" && user_id > 0 {
				res := services.IsLogin(user_id, access_token)
				if res {
					user_service := services.GetUserService(user_id)
					user_info, _ := user_service.GetUserInfo()
					if !utils.Int64InArray(user_info.CompanyIds, company_id) {
						utils.HttpError(c, 403, "非法访问", nil)
						c.Abort()
						return
					}
					var is_inner_user = 0
					if utils.Int64InArray(user_info.Groups, 1) {
						is_inner_user = 1
					}
					if lang == "" {
						lang = user_info.Lang
					}
					c.Set("admin_user", int64(is_inner_user))
					c.Set("user_id", user_id)
					c.Set("company_id", company_id)
					c.Set("login_type", "web")
				}
			}
		}
		if lang == "" {
			lang = "zh_CN"
		}
		c.Set("lang", lang)
		config.Conf.Host = c.Request.Host
		c.Next()
		e.Exit()
		return
	}
}
